#include <stdio.h>
#include <stdlib.h> // exit() / EXIT_FAILURE
#include <unistd.h> // _exit()
#include <fcntl.h> // open() / read() / write() / close()

int main ()
{
    // 打开读的文件，得到文件描述符
    int fd = open("love.txt", O_RDONLY);
    if (fd == -1)
    {
        perror("打开读文件失败");
        exit(EXIT_FAILURE);
        // _exit(EXIT_FAILURE);
    }

    // 打开写的文件
    int fd2 = open("love2.txt", O_CREAT|O_WRONLY|O_APPEND);
    if (fd2 == -1)
    {
        perror("打开写文件失败");
        exit(EXIT_FAILURE);
    }

    // 边读边写
    char buff[1024];
    ssize_t read_size;
    while(read_size=read(fd, buff, sizeof(buff)) > 0)
    {
        write(fd2, buff, read_size);

        // 输出到控制台
        write(STDOUT_FILENO, buff, read_size);
    }

    if (read_size == -1)
    {
        perror("读取文件失败");
        close(fd);
        close(fd2);
        exit(EXIT_FAILURE);
    }

    close(fd);
    close(fd2);
    
    return 0;
}